package cn.edu.sgu.www.mhxysy.util;

import cn.edu.sgu.www.mhxysy.exception.GlobalException;
import cn.edu.sgu.www.mhxysy.restful.ResponseCode;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 读取entity下的实体类映射的表名
 * @author 沐雨橙风ιε
 * @version 1.0
 */
public class TableReaderUtils {

    public static List<String> getTableNames() throws IOException {
        // 包名
        String packageName = "D:/program/IdeaProjects/mhxysy-backend/src/main/java/cn/edu/sgu/www/mhxysy/entity";
        List<String> tableNames = new ArrayList<>();
        File directory = new File(packageName);

        if (directory.exists() && directory.isDirectory()) {
            // 遍历目录下的文件
            File[] list = directory.listFiles();

            if (list != null && list.length > 0) {
                for (File file : list) {
                    File[] array = file.listFiles();

                    if (array != null && array.length > 0) {
                        for (File f : array) {
                            String prefix = "@TableName(\"", suffix = "\")";

                            FileInputStream fis = new FileInputStream(f);
                            InputStreamReader isr = new InputStreamReader(fis);
                            BufferedReader br = new BufferedReader(isr);

                            String line;

                            while ((line = br.readLine()) != null) {
                                if (line.contains(prefix)) {
                                    int start = line.indexOf(prefix);
                                    int end = line.indexOf(suffix);

                                    String tableName = line.substring(start + 12, end);
                                    tableNames.add(tableName);

                                    break;
                                }
                            }
                        }
                    }
                }
            }
        } else {
            throw new GlobalException(ResponseCode.NOT_FOUND, "路径" + directory + "不存在！");
        }

        return tableNames;
    }

    public static void main(String[] args) throws IOException {
        List<String> tableNames = getTableNames();

        System.out.println(tableNames.size());
        System.out.println(tableNames);
    }

}